import os
from uuid import uuid4

from data import config, database

def scan():
    print('Processing files')

    new_files = 0
    found_files_skipped = 0
    files_skipped = 0
    print('Scanning for audio files')
    for parent, _, files in os.walk(config['files']['audio']['path']):
        for file in files:
            path = os.path.join(parent, file)
            for extension in config['files']['audio']['extensions']:
                if path.endswith(extension):
                    break
            else:
                files_skipped += 1
                continue
            db_path = os.path.relpath(path, config['files']['audio']['path'])
            db_path = db_path.replace('\\', '/')
            for uuid in database['music']:
                if database['music'][uuid]['path'] == db_path:
                    found_files_skipped += 1
                    break
            else:
                uuid = uuid4()
                database['music'][uuid] = {
                    'path': db_path,
                    'artists': [],
                    'genre': None,
                    'album': None,
                    'title': file.split('.', -1)[0],
                    'cover': None
                }
                print('Found new track and gave it the UUID %s' % uuid)
                new_files += 1
    print('Skipped %s files' % files_skipped)
    print('Skipped %s files that were already found' % found_files_skipped)
    print('Found %s new files' % new_files)

    new_files = 0
    found_files_skipped = 0
    files_skipped = 0
    print('Scanning for image files')
    for parent, _, files in os.walk(config['files']['images']['path'] if config['files']['images']['path'] else config['files']['audio']['path']):
        for file in files:
            path = os.path.join(parent, file)
            for extension in config['files']['images']['extensions']:
                if path.endswith(extension):
                    break
            else:
                files_skipped += 1
                continue
            db_path = os.path.relpath(path, config['files']['images']['path'] if config['files']['images']['path'] else config['files']['audio']['path'])
            db_path = db_path.replace('\\', '/')
            for uuid in database['covers']:
                if database['covers'][uuid]['path'] == db_path:
                    found_files_skipped += 1
                    break
            else:
                uuid = uuid4()
                database['covers'][uuid] = {
                    'path': db_path,
                    'name': file.split('.', -1)[0]
                }
                print('Found new image and gave it the UUID %s' % uuid)
                new_files += 1
    print('Skipped %s files' % files_skipped)
    print('Skipped %s files that were already found' % found_files_skipped)
    print('Found %s new files' % new_files)
